#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      Sanchez
#
# Created:     15/06/2012
# Copyright:   (c) Sanchez 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import sys
from PyQt4 import QtGui, QtCore
from Ui_MainForm import Ui_MainWindow
from moddt8837 import  *
import pylab as plt
import scipy as sc
from scipy.io.matlab import mio
from datetime import date
import  os
import string

class MonAppli(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        # Configure l'interface utilisateur.
        self.setupUi(self)
        self.DEV1 = "TCPIP::169.254.241.19::INSTR"
        self.h1=0 #handle carte
        self.level=1 # level  1 (1/10V) input
        self.fs=5000 # sampling rate
        self.dt = 1.0/self.fs # period
        self.acqtime=2  #duree 2s
        self.data = []
        self.data = []
        self.sizeHeader =0
        self.sizeBuffer=0
        self.header=[]
        self.v=[]
        self.tab_coupling=["AC","DC"]




#--------------------------------------------------------------------
# menus
#--------------------------------------------------------------------

#--------------------------------------------------------------------
# boutons
#--------------------------------------------------------------------
        self.connect(self.pushButtonStart,QtCore.SIGNAL("clicked()"),On_pushButtonStart)
        self.connect(self.pushButtonConfig,QtCore.SIGNAL("clicked()"),On_pushButtonConfig)
        self.connect(self.pushButtonSenCMD,QtCore.SIGNAL("clicked()"),On_pushButtonSenCMD)



#--------------------------------------------------------------------
# lineEdit
#--------------------------------------------------------------------
        self.connect(self.ProjectName,QtCore.SIGNAL("returnPressed()"),On_ProjectName)
        self.connect(self.FileName,QtCore.SIGNAL("returnPressed()"),On_FileName)
        self.connect(self.SampleRate,QtCore.SIGNAL("returnPressed()"),On_SampleRate)
        self.connect(self.acqTime,QtCore.SIGNAL("returnPressed()"),On_acqTime)

#--------------------------------------------------------------------
# combo bax
#--------------------------------------------------------------------
        self.connect(self.comboBoxCoupling, QtCore.SIGNAL("currentIndexChanged(int)"), OnChange_Coupling)
        self.connect(self.comboBoxLevel, QtCore.SIGNAL("currentIndexChanged(int)"), OnChange_Level)

#--------------------------------------------------------------------
# fonctions des menus
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# fonctions des boutons
#--------------------------------------------------------------------
def On_pushButtonStart():
    print "pushButtonStart"
    w.data = []
    w.data = []
    w.sizeHeader =0
    w.sizeBuffer=0
    w.header=[]
    w.v=[]
    # modification du nom de projet
    w.projectName = str(w.ProjectName.text()).rstrip()
    w.ListInfo.addItem("Project name : "+w.projectName)
    w.ListInfo.scrollToBottom()
    # modification du nom des fichiers"
    w.fileName = str(w.FileName.text()).rstrip()
    w.ListInfo.addItem("Filename name : "+w.fileName)
    w.ListInfo.scrollToBottom()
# creation dossier donnees
    racine=os.getcwd()  # garde la racine
    today = date.today() # date du jour
    s=today.strftime("%Y%m%d") # conversion aaaammjj
    w.path = os.path.join(racine,w.projectName,s)+os.sep
    if not os.path.exists(w.path):
        os.makedirs(w.path, mode=644)
        w.ListInfo.addItem(w.path)
        w.ListInfo.scrollToBottom()

    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("avant armement "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.addItem( "Armement des mesures, pret a lancer ...")
    err1=setAdArm(w.h1)
    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("apres armement "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.addItem("lance la mesure ....")
    err1=setAdInit(w.h1)
    w.ADstatus, w.ideb, w.ifin=GetAdBufferStatus(w.h1)
    w.ListInfo.addItem("mesure lancee "+str(w.ADstatus)+" "+str(w.ideb)+" "+str(w.ifin)+" delta ="+str(w.ifin-w.ideb+1))
    w.ListInfo.scrollToBottom()

    w.tacq=int(w.acqTime.text()) # lecture duree acquisition


    w.buffersize=w.tacq/w.dt # nombre d echantillon pour tacq


    N=200 #254  # work well only with 100 !!!!!!!!!!!!!!!!! or less than 255 (254)


    w.nbblock=int(w.buffersize/N-1)
    time.sleep(w.tacq)  #attente 2s


    err1=setAdStop(w.h1)

    mess=":AD:FETCH? 0,"+str(N)
    print mess
    err1=w.h1.write (mess)
    w.data=w.h1.read_raw()
    #-------------------------------------------------------------------------------
    nomfic=w.path+w.fileName+"_fic_bin_0"+".dat"
    fd = open(nomfic, 'wb')
    fd.write(w.data)
    fd.close()
    #-------------------------------------------------------------------------------


    w.v0,w.v1,w.v2,w.v3=[],[],[],[]

    w.sizeHeader,w.sizeBuffer,w.header,w.buf0,w.buf1,w.buf2,w.buf3 =  readHeader(w.data)
#    w.sizeHeader,w.sizeBuffer,w.header,w.buf =  readHeader(w.data)
    ##print sizeHeader,sizeBuffer
    ##print header


    for i in range(1,w.nbblock):
        mess=":AD:FETCH? "+str(i*N) +","+str(N)
        print mess
        err1=w.h1.write (mess)
        w.data1=w.h1.read_raw()
        #-------------------------------------------------------------------------------
        nomfic=w.path+w.fileName+"_fic_bin_"+str(i)+".dat"
        fd = open(nomfic, 'wb')
        fd.write(w.data1)
        fd.close()
        #-------------------------------------------------------------------------------
        w.sizeHeader,w.sizeBuffer,w.header,w.buf0,w.buf1,w.buf2,w.buf3=  readHeader(w.data1)
#        w.sizeHeader,w.sizeBuffer,w.header,w.buf =  readHeader(w.data1)
        #
        w.v0=np.concatenate(( w.v0,w.buf0), axis=0)
        w.v1=np.concatenate(( w.v1,w.buf1), axis=0)
        w.v2=np.concatenate(( w.v2,w.buf2), axis=0)
        w.v3=np.concatenate(( w.v3,w.buf3), axis=0)
#        w.v=np.concatenate(( w.v,w.buf), axis=0)


    w.v0=raw2volt(w.v0,w.level)
    w.v1=raw2volt(w.v1,w.level)
    w.v2=raw2volt(w.v2,w.level)
    w.v3=raw2volt(w.v3,w.level)
#    w.v=raw2volt(w.v,w.level)


    plt.figure(1)
    plt.hold(True)
    ax1 =plt.subplot(411)
    plt.plot( w.v0,'k.-')
    plt.subplot(412, sharex=ax1)
    plt.plot( w.v1,'b.-')
    plt.subplot(413, sharex=ax1)
    plt.plot( w.v2,'r.-')
    plt.subplot(414, sharex=ax1)
    plt.plot( w.v3,'g.-')
#sauvegarde binaire, les vois se suivent
    nomfic=w.path+w.fileName+"_bin"+".dat"
    fd = open(nomfic, 'wb')
    fd.write(w.v0)
    fd.write(w.v1)
    fd.write(w.v2)
    fd.write(w.v3)
#    fd.write(w.v)
    fd.close()

#-------------------------------------------------------------
#   sauvegarde matfile
#--------------------------------------------------------------
    data = {}
    data['v0'] = w.v0    # variable matlab
    data['v1'] = w.v1    # variable matlab
    data['v2'] = w.v2    # variable matlab
    data['v3'] = w.v3    # variable matlab
    data['fs'] = w.fs    #sampling rate
    data['level'] = w.level    # level 1/10
    data['coupling'] = w.coupling  # AC/DC

    data['timelength'] = w.tacq    # time length

    outmatfile=w.path+w.fileName+"_mat"+".mat"
    sc.io.savemat(outmatfile,data)
    doRST(w.h1)
    plt.show()
    return


def On_pushButtonConfig():
    print "pushButtonConfig"
    # modification du nom de projet
    w.projectName = str(w.ProjectName.text()).rstrip()
    w.ListInfo.addItem("Project name : "+w.projectName)
    w.ListInfo.scrollToBottom()
    # modification du nom des fichiers"
    w.fileName = str(w.FileName.text()).rstrip()
    w.ListInfo.addItem("Filename name : "+w.fileName)
    w.ListInfo.scrollToBottom()
# creation dossier donnees
    racine=os.getcwd()  # garde la racine
    today = date.today() # date du jour
    s=today.strftime("%Y%m%d") # conversion aaaammjj
    w.path = os.path.join(racine,w.projectName,s)+os.sep
    if not os.path.exists(w.path):
        os.makedirs(w.path, mode=644)
        w.ListInfo.addItem(w.path)
        w.ListInfo.scrollToBottom()



    w.h1 = getHandle(w.DEV1)
    mess=getID(w.h1)
    w.ListInfo.addItem("Device name : "+mess)
    w.ListInfo.addItem(" Enable AD for all channel")
    doRST(w.h1)
    err1 = setAdEnableAll(w.h1)
    w.ListInfo.addItem("Channel coupling AC ...")
    w.coupling="AC"
    err1 = setCouplage(w.h1,'AC')
    w.ListInfo.addItem("Init level ...")
    w.level=1   # 1V en entree 1 ou 10
    err1 = setGain(w.h1,w.level)
    w.ListInfo.addItem("Mode  buffer wrap/no wrap ...")
    err1 = setWrap(w.h1,"off")  #   buffer circulaire off
    w.h1.write("ad:buffer:size?")
    mess = w.h1.read()
    w.ListInfo.addItem("Buffer size : "+mess)
    w.ListInfo.addItem("Initialisation horloge interne ...")
    err1=setADClockInternal(w.h1)
    w.ListInfo.addItem("Initialisation frequence horloge interne ...")
    w.fs=int(w.SampleRate.text()) # lecture freq ech Hz
    err1=setFreqClock(w.h1,w.fs)
    w.dt=1.0/w.fs    #periode echantillonnange
    w.ListInfo.addItem("Sampling rate : "+str(w.fs)+" hz")
    w.ListInfo.addItem("Init source trigger immediat ...")
    err1=setAdTrigSourceImm(w.h1)

    return


def On_pushButtonSenCMD():
    print "pushButtonSenCMD"
    mess=str(w.lineEditmessSCPI.text()).rstrip()
    w.ListInfo.addItem("mess : "+mess)
    err=w.h1.write(mess+"\n")  # recup commande
    ret=w.h1.read()
    w.ListInfo.addItem("Rep : "+ret)
    return
#--------------------------------------------------------------------
# fonctions des LineEdit
#--------------------------------------------------------------------
def On_ProjectName():
    " get w.ProjectName.text()  faire la conversion vers int ou float"
    print "ProjectName"
    pass
    return

def On_FileName():
    " get w.FileName.text()  faire la conversion vers int ou float"
    print "FileName"
    pass
    return

def On_SampleRate():
    " get w.SampleRate.text()  faire la conversion vers int ou float"
    print "SampleRate"
    pass
    return

def On_acqTime():
    " get w.acqTime.text()  faire la conversion vers int ou float"
    print "acqTime"
    pass
    return
#--------------------------------------------------------------------
# fonction des combo box
#-------------------------------------------------------------------
def OnChange_Coupling(couplage):
    w.couplage=couplage
    w.ListInfo.addItem("couplage : "+w.tab_coupling[w.couplage])
    if (w.tab_coupling[w.couplage]=="AC"):
        w.ListInfo.addItem("Channel coupling AC ...")
        err1 = setCouplage(w.h1,'AC')
        w.coupling="AC"
    elif (w.tab_coupling[w.couplage]=="DC"):
        w.ListInfo.addItem("Channel coupling DC ...")
        err1 = setCouplage(w.h1,'DC')
        w.coupling="DC"

def OnChange_Level(level):
    w.indlevel=level
    if w.indlevel==0:
        w.level=1
        w.ListInfo.addItem("Init level 1...")
        err1 = setGain(w.h1,w.level)
    elif w.indlevel==1:
        w.level=10
        w.ListInfo.addItem("Init level 10...")
        err1 = setGain(w.h1,w.level)
    w.ListInfo.addItem("gain : "+str(w.level))



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MonAppli()

    w.show()
    sys.exit(app.exec_())
